package com.wlit;

import gnu.io.*;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class SerialDemo {

    public static void main(String[] args) throws Exception {
        String portName = "COM3";
        CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);

        CommPort commPort = commPortIdentifier.open(portName, 5000);

        SerialPort serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.notifyOnDataAvailable(true);
        InputStream inputStream = serialPort.getInputStream();
        OutputStream outputStream = serialPort.getOutputStream();
        serialPort.addEventListener(new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent p0) {
                if (p0.getEventType() == SerialPortEvent.DATA_AVAILABLE){
                    Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        System.out.println(line);
                    }
                }
            }
        });


        //byte[] bb = ByteBufUtil.decodeHexDump("01B20016CBAEC9EE32C3D72CCEA3CFD52CC7EBCEF0BDD3BDFC00E907");
//        String str = "01B2001BB5B1C7B0CBAECEBBBDCFC9EEA3ACD7A2D2E2D0D0B3B5B0B2C8AB002659";
//        byte[] bb = ByteBufUtil.decodeHexDump(str);
        byte[] bb = buildData();
        System.out.println(ByteBufUtil.prettyHexDump(Unpooled.wrappedBuffer(bb)).toUpperCase());
        outputStream.write(bb);
        outputStream.flush();

        Thread.sleep(1000);
        serialPort.close();
    }

    public static byte[] buildData() throws Exception{
        byte[] result = buildVoice();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.write(result);
        int crc = CRC16Utils.calculate(result);
        dos.writeShort(crc);
        return baos.toByteArray();
    }

    public static byte[] buildVoice() throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        baos.write(0x01);
        baos.write(0xB2);
        String voice = "时间到了";
        byte[] gbk = voice.getBytes("GBK");
        dos.writeShort(gbk.length+1);
        dos.write(gbk);
        dos.write(0x00);
        return baos.toByteArray();
    }
}
